package com.yc.Testjvm.hotload;

import java.io.File;
import java.lang.reflect.Method;

public class HelloMain {
	
	//共享类和对象
	public static volatile Class desClzz;
	public static volatile Object desObj;
	
	public static Long REFRESH_TIME = 3000L;//3秒刷新一次

	//主线程只负责使用类对象，不管对象是怎么来的(或者有没有改变)
	public static void main(String[] args) {
		//监听并改变类和对象
		new Thread(new classFileListen("com.yc.Testjvm.hotload.Worker")).start();
		
		//主线程
		try {
			while(true) {
				if (null != desClzz && null != desObj) {
					Method excuteClazzMethod = desClzz.getMethod("doIt", null);
		            excuteClazzMethod.invoke(desObj, null);//执行
				}
	            Thread.sleep(5000);//模拟5秒钟需要调用一次方法
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}

/**
 * 监听类文件，改变后，重新生成类和对象
 * @author yuancan
 *
 */
class classFileListen implements Runnable{
	
	private String classFullName;
	private File classFile;
	private Long lastModifyTime;
	private Long nowTime;
	
	public classFileListen(String name) {
		classFullName = name;
		//获取文件当前修改时间
		classFile = new File(ExtNewClassLoad.ExtClassPath + classFullName.replace(".", "/") + ".class");
		lastModifyTime = classFile.lastModified();
	}

	@Override
	public void run() {
		try {
			while(true) {
				classFile = new File(ExtNewClassLoad.ExtClassPath + classFullName.replace(".", "/") + ".class");
				nowTime = classFile.lastModified();
				if (HelloMain.desClzz != null && lastModifyTime.equals(nowTime)) {
					Thread.sleep(HelloMain.REFRESH_TIME);//如果没变，3秒后再检查一次
					continue;
				}
				lastModifyTime = nowTime;
				ExtNewClassLoad classload = new ExtNewClassLoad();
				HelloMain.desClzz = classload.findClass(classFullName);
				HelloMain.desObj = HelloMain.desClzz.getConstructor(new Class[]{}).newInstance(new Object[]{});
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
}